package com.jjlin.chapter_3;
import java.util.*;
public class CD170{
    //二叉树节点
    public static class Node{
        public int val;
        public Node left;
        public Node right;
        public Node(int data){
            this.val = data;
        }
    }

    //建立二叉树
    public static Node createNodeList(int[][] nums, int root){
        if(nums == null || nums.length == 0 || nums[0] == null || nums[0].length == 0)
            return null;
        HashMap<Integer, Node> map = new HashMap<>();
        for(int i = 0; i < nums.length; ++i){
            map.putIfAbsent(nums[i][0], new Node(nums[i][0]));
            if(nums[i][1] != 0){
                map.putIfAbsent(nums[i][1], new Node(nums[i][1]));
                map.get(nums[i][0]).left = map.get(nums[i][1]);
            }
            if(nums[i][2] != 0){
                map.putIfAbsent(nums[i][2], new Node(nums[i][2]));
                map.get(nums[i][0]).right = map.get(nums[i][2]);
            }
        }
        return map.get(root);
    }

    //判断t1树是否包含t2树的全部的拓扑结构
    public static boolean contains(Node t1, Node t2){
        boolean flag = check(t1, t2);
        if(flag)
            return true;
        if(t1 != null)
            return contains(t1.left, t2) || contains(t1.right, t2);
        return false;
    }

    public static boolean check(Node t1, Node t2){
        if(t2 == null)
            return true;
        if(t1 == null || t1.val != t2.val)
            return false;
        return check(t1.left, t2.left) && check(t1.right, t2.right);
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int root = sc.nextInt();
        int[][] nums = new int[n][3];
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < 3; ++j)
                nums[i][j] = sc.nextInt();
        Node head1 = createNodeList(nums, root);
        n = sc.nextInt();
        root = sc.nextInt();
        nums = new int[n][3];
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < 3; ++j)
                nums[i][j] = sc.nextInt();
        Node head2 = createNodeList(nums, root);
        System.out.println(contains(head1, head2));
    }
}

